<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="120px">
        <div class="sa-color--warning sa-m-l-50 sa-m-b-18"
          >在小程序直播控制台添加的商品，不支持通过此系统操作。</div
        >
        <el-form-item label="商品来源">
          <el-radio-group v-model="form.model.type">
            <el-radio :label="0">我的小程序</el-radio>
            <el-radio :label="1">其他小程序</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品选择" prop="goods_id" v-if="form.model.type === 0">
          <el-button type="primary" class="is-link" @click="selectGoods" v-if="!form.model.goods_id"
            >选择商品</el-button
          >
          <div class="sa-template-content sa-template-goods" v-if="form.model.goods_id">
            <div class="header sa-flex">
              <div class="item">商品信息</div>
              <div class="oper">操作</div>
            </div>
            <div class="list sa-flex">
              <div class="item sa-flex">
                <sa-image :url="goods.image" size="40"></sa-image>
                <div class="sa-m-l-8">
                  <div class="title">{{ goods.title }}</div>
                </div>
              </div>
              <div class="oper">
                <el-button class="is-link" type="danger" @click="deleteItems()">移除</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="商品封面">
          <sa-uploader v-model="form.model.cover_img_url" fileType="image" isCropper></sa-uploader>
          <div class="desc sa-m-l-12"> 图片尺寸最大300像素*300像素 </div>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="form.model.name"
            :maxlength="14"
            :minlength="3"
            show-word-limit
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格形式" prop="price_type">
          <el-radio-group v-model="form.model.price_type">
            <el-radio :label="1">一口价</el-radio>
            <el-radio :label="2">价格区间</el-radio>
            <el-radio :label="3">显示折扣价</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="价格">
          <div class="sa-m-r-8" v-if="form.model.price_type !== 1">{{
            form.model.price_type === 2 ? '最小价格' : '市场价'
          }}</div>
          <el-input
            v-model="form.model.price"
            placeholder="请输入价格"
            class="sa-w-160"
            type="number"
            :step="0.01"
            :min="0"
            :precision="2"
          >
            <template #append>元</template>
          </el-input>
          <div class="sa-m-l-16 sa-m-r-8" v-if="form.model.price_type !== 1">{{
            form.model.price_type === 2 ? '最大价格' : '现价'
          }}</div>
          <el-input
            v-model="form.model.price2"
            placeholder="请输入价格"
            class="sa-w-160"
            type="number"
            :step="0.01"
            :min="0"
            :precision="2"
            v-if="form.model.price_type !== 1"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="APPID" prop="third_party_appid" v-if="form.model.type === 1">
          <el-input
            v-model="form.model.third_party_appid"
            placeholder="请输入该小程序APPID"
          ></el-input>
        </el-form-item>

        <el-form-item label="商品路径" prop="url">
          <div>
            <el-input v-model="form.model.url" placeholder="请输入商品路径"></el-input>
            <div class="desc">
              请确保小程序页面路径可被访问。例如：pages/goods/index?query=value
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.app.mplive.goods.add'"
        type="primary"
        @click="confirm"
        >保存</el-button
      >
      <el-button
        v-if="modal.params.type == 'edit'"
        v-auth="'shop.admin.app.mplive.goods.edit'"
        type="primary"
        @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../../app.service';
  import { cloneDeep } from 'lodash';
  import GoodsSelect from '@/app/shop/admin/goods/goods/select.vue';
  import { useModal } from '@/sheep/hooks';
  import { api as goodsApi } from '@/app/shop/admin/goods/goods.service';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      type: 0,
      name: '',
      price_type: 1,
      third_party_appid: '',
      price: '',
      price2: '',
      cover_img_url: '',
    },
    rules: {
      name: [{ validator: checkTitle, trigger: 'change' }],
      cover_img_url: [{ required: true, message: '请选择商品封面', trigger: 'change' }],
    },
  });
  const goods = reactive({
    id: '', // 商品id
    image: '', // 商品图片
    title: '', // 商品名称
  });
  const loading = ref(false);

  function checkTitle(rule, value, callback) {
    if (!value) {
      return callback(new Error('请输入商品名称'));
    }
    const length =
      value.match(/[^ -~]/g) == null ? value.length : value.length + value.match(/[^ -~]/g).length;
    if (length < 6 || length > 28) {
      callback(new Error('直播标题必须为3-14个字（一个字等于两个英文字符或特殊字符）'));
    } else {
      callback();
    }
  }
  // 获取商品信息
  async function getGoodsList(id) {
    const { data } = await goodsApi.goods.select(
      {
        search: JSON.stringify({ id }),
      },
      'select',
    );
    goods.image = data[0].image;
    goods.title = data[0].title;
  }

  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { error, data } = await api.mplive.goods.detail(id);
    if (error === 0) {
      form.model = data;
      getGoodsList(form.model.goods_id);
    }
    loading.value = false;
  }

  // 表单关闭时提交
  async function confirm() {
    // 表单验证
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      loading.value = true;
      let submitForm = cloneDeep(form.model);
      const { error } =
        props.modal.params.type == 'add'
          ? await api.mplive.goods.add(submitForm)
          : await api.mplive.goods.edit(props.modal.params.id, submitForm);
      if (error == 0) {
        emit('modalCallBack', { event: 'confirm' });
      }
      loading.value = false;
    });
  }
  //选择商品
  function selectGoods() {
    let id = '';
    useModal(
      GoodsSelect,
      {
        title: '选择商品',
        id,
      },
      {
        confirm: (res) => {
          goods.image = res.data.image;
          goods.title = res.data.title;
          goods.id = res.data.id;

          form.model.cover_img_url = res.data.image;
          form.model.name = res.data.title;
          form.model.url = 'pages/goods/index?id=' + goods.id;
          if (res.data.price.length === 2) {
            form.model.price_type = 2;
            form.model.price = res.data.price[0];
            form.model.price2 = res.data.price[1];
          } else {
            if (Number(res.data.original_price)) {
              form.model.price_type = 3;
              form.model.price = res.data.original_price;
              form.model.price2 = res.data.price[0];
            } else {
              form.model.price_type = 1;
              form.model.price = res.data.price[0];
            }
          }
          form.model.goods_id = res.data.id;
        },
      },
    );
  }
  function deleteItems() {
    form.model.goods_id = '';
  }
  async function init() {
    if (props.modal.params.id) {
      await getDetail(props.modal.params.id);
    }
  }

  onMounted(() => {
    init();
  });
</script>
<style lang="scss" scoped>
  .desc {
    font-size: 14px;
    color: #999999;
  }
</style>
